#include "Unit_Move.h"

#include "../Game.h"
#include "../GameControl.h"
#include "../../tools/Log.h"

#include <cstring>

string Unit_Move::command = "move unit";

string Unit_Move::toString() { return string(serialize().data); }

Unit_Move::Unit_Move(unsigned long Id, unsigned X, unsigned Y)
{
	id = Id;
	x = X;
	y = Y;
}

SerializedGameCommand Unit_Move::serialize() const
{
	SerializedGameCommand cmd;
	sprintf(cmd.data, "%s %lu %u %u %lu", command.c_str(), id, x, y, timestamp);
	return cmd;
}

Unit_Move* Unit_Move::interpret(const SerializedGameCommand& sgc)
{
	if (strncmp(sgc.data, command.c_str(), command.size()) == 0)
	{
		Unit_Move* cmd = new Unit_Move();
		if(sscanf(sgc.data, "move unit %lu %u %u %lu", &(cmd->id), &(cmd->x), &(cmd->y), &(cmd->timestamp)) == 4)
			return cmd;
	}
	
	return NULL;
}

Unit_Move* Unit_Move::interpret(const char* line)
{
	if (strncmp(line, command.c_str(), command.size()) == 0)
	{
		Unit_Move* cmd = new Unit_Move();
		if(sscanf(line, "move unit %lu %u %u %lu", &(cmd->id), &(cmd->x), &(cmd->y), &(cmd->timestamp)) == 4)
			return cmd;
		else if(sscanf(line, "move unit %lu %u %u", &(cmd->id), &(cmd->x), &(cmd->y)) == 3)
			return cmd;
		
		lout << Unit_Move::command << " error: Invalid arguments" << endl;
		delete cmd;
	}
	
	return NULL;
}

void Unit_Move::onExecute()
{
	// -- BEGIN CUSTOM CODE REGION -- //	
	Game::Instance()->move_unit(id, x, y);
	// -- END CUSTOM CODE REGION -- //
}
